package com.zhengdongzulin.zuke.app.main.apartment.sign

import android.content.Intent
import android.graphics.Color
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.widget.EditText
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.Utils
import com.luck.picture.lib.tools.ScreenUtils.dip2px
import com.lxj.androidktx.core.*
import com.lxj.easyadapter.ViewHolder
import com.zhengdongzulin.zuke.R
import com.zhengdongzulin.zuke.app.data.ContractListData
import com.zhengdongzulin.zuke.app.data.Roommate
import com.zhengdongzulin.zuke.app.main.ZKWebviewActivity
import com.zhengdongzulin.zuke.base.*
import com.zhengdongzulin.zuke.databinding.ZkActivitySign3Binding
import com.zhengdongzulin.zuke.ext.*
import razerdp.basepopup.BasePopupWindow
import razerdp.util.animation.AnimationHelper
import razerdp.util.animation.TranslationConfig
import com.luck.picture.lib.entity.LocalMedia

import com.luck.picture.lib.listener.OnResultCallbackListener

import com.zhengdongzulin.zuke.picture.GlideEngine

import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureSelectionConfig.listener
import java.io.File


class ZKSign3Activity : BaseActivity<SignVm, ZkActivitySign3Binding>() {

    var mData = mutableListOf<ContractListData>()
    var mRoommateList = arrayListOf<Roommate>()
    lateinit var mPop: BasePopupWindow

    override fun getLayoutResId(): Int = R.layout.zk_activity_sign3

    override fun initVM(): SignVm = getVM(SignVm::class.java)

    override fun initView() {
        isInitDialog = true
        setTitleContent("填写租房资料")
        mView.tvSign3RealName.setText(intent.getStringExtra("name")!!)
        mView.tvSign3IdCardNo.setText(intent.getStringExtra("idCardNo")!!)

    }

    override fun initData() {

        mView.recyclerView.vertical().bindData(
            mRoommateList,
            R.layout.item_sign3
        ) { holder: ViewHolder, item: Roommate, position: Int ->
            //选择证件类型
            holder.getView<LinearLayout>(R.id.ll_select_card_type).setOnClickListener {
            }
            holder.getView<EditText>(R.id.et_name).addTextChangedListener(object : MyTextWatcher() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    mRoommateList[position].name = s.toString()
                }
            })
            holder.getView<EditText>(R.id.et_phone)
                .addTextChangedListener(object : MyTextWatcher() {
                    override fun onTextChanged(
                        s: CharSequence?,
                        start: Int,
                        before: Int,
                        count: Int
                    ) {
                        mRoommateList[position].phone = s.toString()
                    }
                })
            holder.getView<EditText>(R.id.et_id_card_no)
                .addTextChangedListener(object : MyTextWatcher() {
                    override fun onTextChanged(
                        s: CharSequence?,
                        start: Int,
                        before: Int,
                        count: Int
                    ) {
                        mRoommateList[position].idCardNo = s.toString()
                    }
                })
            holder.setOnClickListenerr(R.id.tv_select_card_tppe) {
                var viewGroup = layoutInflater.inflate(R.layout.pop_card_type, null)
                var recycler = viewGroup.findViewById<RecyclerView>(R.id.recyclerView)
                recycler.vertical().bindData(
                    arrayListOf("身份证", "护照", "港澳通行证", "台湾同胞证"),
                    R.layout.item_card_type
                ) { holder, t, position ->
                    holder.setText(R.id.name, t)
                }.itemClick { data: List<String>, holder, position2 ->
                    it.text = data[position2]
                    mRoommateList[position].cardType = "${position2 + 1}"
                    mPop.dismiss()
                }
                mPop = object : BasePopupWindow(this) {
                    override fun onCreateShowAnimation(): Animation {
                        return AnimationHelper.asAnimation()
                            .withTranslation(TranslationConfig.FROM_TOP)
                            .toShow()
                    }

                    override fun onCreateDismissAnimation(): Animation {
                        return AnimationHelper.asAnimation()
                            .withTranslation(TranslationConfig.TO_TOP)
                            .toDismiss()
                    }
                }.apply {
                    contentView = viewGroup
                    setPopupGravity(Gravity.BOTTOM)
                    setWidth(it.width)
                    setBackgroundColor(Color.TRANSPARENT)
                }
                mPop.showPopupWindow(it)
            }
            holder.getView<View>(R.id.iv_clear_roommate).setOnClickListener {
                mRoommateList.removeAt(position)
                mView.recyclerView.adapter?.notifyDataSetChanged()
            }
        }
    }

    open inner class MyTextWatcher : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }

        override fun afterTextChanged(s: Editable?) {
        }
    }

    var ivTiiPicOnePath = ""
    var ivTiiPicTwoPath = ""


    var zukeSfzZheng = ""
    var zukeSfzFan = ""


    override fun initListener() {
        mView.llAddRoommate.setOnClickListener {
            mRoommateList.add(Roommate("", "", "1", ""))
            mView.recyclerView.adapter!!.notifyDataSetChanged()
        }
        mView.tvCommit.setOnClickListener {
            commit()
        }
        mView.ivTiiPicOne.setOnClickListener {
            openSingleGallery { boolean: Boolean, path: String ->
                //loge("$boolean -------  $path")
                if (boolean) {
                    ivTiiPicOnePath = path
                    mView.ivTiiPicOne.loadImage(path)
                }
            }
        }
        mView.ivTiiPicTwo.setOnClickListener {
            openSingleGallery { boolean: Boolean, path: String ->
                //loge("$boolean -------  $path")
                if (boolean) {
                    ivTiiPicTwoPath = path
                    mView.ivTiiPicTwo.loadImage(path)
                }
            }
        }
    }

    override fun startObserve() {
        mViewModel.sign_online.observe(this) {
            if (!it.signUrl.isNullOrEmpty()) {
                Intent().put("url", it.signUrl).put("title", "在线签字").start(
                    this@ZKSign3Activity,
                    ZKWebviewActivity::class.java
                )
                removeActivitys(ZKSign1Activity::class.java, ZKSign2Activity::class.java)
                finish()
            } else {
                toast("签约url为空")
            }
        }
        mViewModel.sign_online.state.observe(this, getObserver(mViewModel.sign_online))

        mViewModel.upload.observe(this) {
            if ("zukeSfzZheng".equals(it.name)) {
                zukeSfzZheng = it.url
                mViewModel.upload(File(ivTiiPicTwoPath), "zukeSfzFan")
                return@observe
            }
            if ("zukeSfzFan".equals(it.name)) {
                zukeSfzFan = it.url
            }
            if (!TextUtils.isEmpty(zukeSfzZheng) && !TextUtils.isEmpty(zukeSfzFan)) {
                signOnline()
            }
        }
        mViewModel.upload.state.observe(this, getObserver(mViewModel.upload))
    }

    fun commit() {
        var emergencyPeo = mView.tvSign3EmergencyPeo.getTextZ()
        var emergencyPeoPhone = mView.tvSign3EmergencyPeoPhone.getTextZ()

        if (TextUtils.isEmpty(ivTiiPicOnePath)) {
            toast("请选择身份证正面")
            return
        }
        if (TextUtils.isEmpty(ivTiiPicTwoPath)) {
            toast("请选择身份证反面")
            return
        }

        if (emergencyPeo.isEmpty()) {
            toast("请输入紧急联系人姓名")
            return
        }
        if (emergencyPeoPhone.isEmpty()) {
            toast("请输入紧急联系人电话")
            return
        }
        if (!mView.tvSign3EmergencyPeoPhone.contrast(11)) {
            toast("请输入11位紧急联系人电话")
            return
        }
        if (!mView.tvSign3EmergencyPeoPhone.checkPhone()) {
            toast("请输入正确的紧急联系人电话")
            return
        }

        if (mView.tvSign3EmergencyPeoAddress.isEmpty()) {
            toast("请输入紧急联系人联系地址")
            return
        }
        if (mView.tvSign3EmergencyPeoEmail.isEmpty()) {
            toast("请输入紧急联系人邮箱")
            return
        }

        for (roommate in mRoommateList) {
        }

        mViewModel.upload(File(ivTiiPicOnePath), "zukeSfzZheng")


    }

    fun signOnline() {
        var emergencyPeo = mView.tvSign3EmergencyPeo.getTextZ()
        var emergencyPeoPhone = mView.tvSign3EmergencyPeoPhone.getTextZ()
        mViewModel.sign_online(
            houseId = intent.getStringExtra("houseId")!!,
            channelSourceId = intent.getStringExtra("ChannelSourceId")!!,
            emergencyPeo = emergencyPeo,
            emergencyPeoPhone = emergencyPeoPhone,
            payTypeId = intent.getStringExtra("payTypeId")!!,
            startDate = intent.getStringExtra("startDate")!!,
            endDate = intent.getStringExtra("endDate")!!,
            roommateList = mRoommateList,
            zukeSfzZheng = zukeSfzZheng,
            zukeSfzFan = zukeSfzFan,

            emergencyemail = mView.tvSign3EmergencyPeoEmail.getTextZ(),
            emergencyhomeAddress = mView.tvSign3EmergencyPeoAddress.getTextZ(),
        )
    }
}